package wowraidmanager.client.wishlist.user;

import java.util.ArrayList;

import wowraidmanager.client.BaseComposite;
import wowraidmanager.client.service.wishlist.MemberBackupService;
import wowraidmanager.client.service.wishlist.MemberBackupServiceAsync;
import wowraidmanager.client.service.wishlist.MemberService;
import wowraidmanager.client.service.wishlist.MemberServiceAsync;
import wowraidmanager.shared.model.wishlist.Droplist;
import wowraidmanager.shared.model.wishlist.Member;
import wowraidmanager.shared.model.wishlist.MemberBackup;
import wowraidmanager.shared.model.wishlist.UserStatus;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class Restoreuserlist extends BaseComposite{

    private static RestoreuserlistUiBinder uiBinder = GWT.create(RestoreuserlistUiBinder.class);

    protected MemberServiceAsync memberService = GWT.create(MemberService.class);

    protected MemberBackupServiceAsync memberBackupService = GWT.create(MemberBackupService.class);

    interface RestoreuserlistUiBinder extends UiBinder<Widget, Restoreuserlist>{
    }

    static int COLUMN_GUILD = 0;
    static int COLUMN_REALM = 1;
    static int COLUMN_MEMBERNAME = 2;
    static int COLUMN_MEMBERTYPE = 3;
    static int COLUMN_MEMBERACCOUNT = 4;
    static int COLUMN_ORDER = 5;
    static int COLUMN_WISHLIST = 6;
    static int COLUMN_RESTORE = 7;
    static int COLUMN_HIDDENKEY = 8;

    static int COLUMN_RAIDZONE = 0;
    static int COLUMN_BOSSNAME = 1;
    static int COLUMN_ITEMLINK = 2;

    UserStatus userStatus;

    ArrayList<MemberBackup> memberBackupList;

    @UiField
    ListBox dateListbox;

    @UiField
    Label selectDateLabel;

    @UiField
    FlexTable restoreFlextable;

    @UiField
    Label wishlistLabel;

    @UiField
    FlexTable wishlistFlextable;

    public Restoreuserlist(UserStatus userStatus){
        initWidget(uiBinder.createAndBindUi(this));

        this.userStatus = userStatus;
        getMemberbackupList();
    }

    private void getMemberbackupList(){

        memberBackupService.getMemberBackupList(userStatus, new AsyncCallback<ArrayList<MemberBackup>>(){

            public void onSuccess(ArrayList<MemberBackup> result){
                memberBackupList = result;
                setMemberBackup();
            }

            public void onFailure(Throwable caught){
                clearInfoMessage();
                setErrorMessage("MemberBackupの取得に失敗しました。");
            }
        });
    }

    protected void setMemberBackup(){
        setDateListBox();
    }

    private void setMemberBackupFlexTable(String date){
        DateTimeFormat formatter = DateTimeFormat.getFormat("yyyy/MM/dd");

        selectDateLabel.setText("Select " + date + "'s Data");
        restoreFlextable.setBorderWidth(1);

        restoreFlextable.removeAllRows();
        int row = 0;
        restoreFlextable.setText(row, COLUMN_GUILD, "Guild");
        restoreFlextable.setText(row, COLUMN_REALM, "Realm");
        restoreFlextable.setText(row, COLUMN_MEMBERNAME, "MemberName");
        restoreFlextable.setText(row, COLUMN_MEMBERTYPE, "MemberType");
        restoreFlextable.setText(row, COLUMN_MEMBERACCOUNT, "MemberAccount");
        restoreFlextable.setText(row, COLUMN_ORDER, "Order");
        restoreFlextable.setText(row, COLUMN_WISHLIST, "CheckWishlist");
        restoreFlextable.setText(row, COLUMN_RESTORE, "Restore");

        row++;

        for(MemberBackup memberBackup:memberBackupList){
            String value = formatter.format(memberBackup.getBackupDate());
            if(date.equals(value)){

                restoreFlextable.setText(row, COLUMN_GUILD, memberBackup.getGuild());
                restoreFlextable.setText(row, COLUMN_REALM, memberBackup.getRealm());
                restoreFlextable.setText(row, COLUMN_MEMBERNAME, memberBackup.getMemberName());
                restoreFlextable.setText(row, COLUMN_MEMBERTYPE, memberBackup.getMembertype());
                restoreFlextable.setText(row, COLUMN_MEMBERACCOUNT, memberBackup.getMemberAccount());
                restoreFlextable.setText(row, COLUMN_ORDER, String.valueOf(memberBackup.getOrder()));

                Button wishlistButton = new Button("Wishlist");
                restoreFlextable.setWidget(row, COLUMN_WISHLIST, wishlistButton);
                restoreFlextable.getCellFormatter().setHorizontalAlignment(row, COLUMN_WISHLIST, HasHorizontalAlignment.ALIGN_CENTER);

                Button restoreButton = new Button("Restore");
                restoreFlextable.setWidget(row, COLUMN_RESTORE, restoreButton);
                restoreFlextable.getCellFormatter().setHorizontalAlignment(row, COLUMN_RESTORE, HasHorizontalAlignment.ALIGN_CENTER);

                setButton(wishlistButton, restoreButton, memberBackup);

                row++;
            }
        }

        wishlistLabel.setVisible(false);
        wishlistFlextable.setVisible(false);
    }

    private void setDateListBox(){
        ArrayList<String> dateList = getDate();
        for(String date:dateList){
            dateListbox.addItem(date);
        }

        dateListbox.addChangeHandler(new ChangeHandler(){

            public void onChange(ChangeEvent event){
                String date = dateListbox.getItemText(dateListbox.getSelectedIndex());
                setMemberBackupFlexTable(date);
            }
        });

        setMemberBackupFlexTable(dateListbox.getItemText(0));
    }

    private ArrayList<String> getDate(){
        ArrayList<String> dateList = new ArrayList<String>();
        DateTimeFormat formatter = DateTimeFormat.getFormat("yyyy/MM/dd");

        for(MemberBackup memberBackup:memberBackupList){
            String value = formatter.format(memberBackup.getBackupDate());
            if(!dateList.contains(value)){
                dateList.add(value);
            }
        }

        return dateList;
    }

    private void setButton(Button wishlistButton, Button restoreButton, final MemberBackup memberBackup){
        wishlistButton.addClickHandler(new ClickHandler(){

            public void onClick(ClickEvent event){
                setWishlist(memberBackup);
            }
        });

        restoreButton.addClickHandler(new ClickHandler(){

            public void onClick(ClickEvent event){
                setRestore(memberBackup);
            }
        });
    }

    protected void setRestore(MemberBackup memberBackup){
        new RestoreDialog(memberBackup, this).show();
    }

    protected void setWishlist(MemberBackup memberBackup){
        wishlistLabel.setVisible(true);
        wishlistFlextable.setVisible(true);

        wishlistLabel.setText(memberBackup.getMemberName() + "'s Wishlist");
        wishlistFlextable.setBorderWidth(1);
        wishlistFlextable.removeAllRows();

        int row = 0;
        wishlistFlextable.setText(row, COLUMN_RAIDZONE, "RaidZone");
        wishlistFlextable.setText(row, COLUMN_BOSSNAME, "BossName");
        wishlistFlextable.setText(row, COLUMN_ITEMLINK, "Item");

        row++;

        if(memberBackup.getWishlist() != null){
            for(Droplist droplist:memberBackup.getWishlist()){
                wishlistFlextable.setText(row, COLUMN_RAIDZONE, droplist.getRaidzone());
                wishlistFlextable.setText(row, COLUMN_BOSSNAME, droplist.getBossName());
                wishlistFlextable.setHTML(row, COLUMN_ITEMLINK, "<a href=\"http://www.wowhead.com/item=" + droplist.getId() + "\" rel=\"item=" + droplist.getId() + "\" class=\"q" + (Integer.valueOf(droplist.getItemColor()) + 1) + "\" target=\"_blank\">[" + droplist.getItemName() + "]</a>");
                row++;
            }
        }
    }

    private class RestoreDialog extends DialogBox{

        public RestoreDialog(final MemberBackup memberBackup, Restoreuserlist restoreuserlist){
            setText("Restore Dialog");
            setAnimationEnabled(true);
            setGlassEnabled(true);

            HTMLPanel content = new HTMLPanel("");
            Label deleteLabel = new Label("本当に以下のユーザを復元しますか？");
            Label userLabel = new Label("MemberName:" + memberBackup.getMemberName());
            Label dateLabel = new Label("Date:" + memberBackup.getBackupDate());

            Button okButton = new Button("OK");
            okButton.addClickHandler(new ClickHandler(){
                public void onClick(ClickEvent event){
                    RestoreDialog.this.hide();
                    restoreMember(memberBackup);
                }
            });

            Button cancelButton = new Button("Cancel");
            cancelButton.addClickHandler(new ClickHandler(){
                public void onClick(ClickEvent event){
                    RestoreDialog.this.hide();
                }
            });

            content.add(deleteLabel);
            content.add(userLabel);
            content.add(dateLabel);
            content.add(okButton);
            content.add(cancelButton);
            add(content);

            setPopupPosition(restoreuserlist.getOffsetWidth() / 2 - content.getOffsetWidth(), restoreuserlist.getOffsetHeight() / 2);
        }

        protected void restoreMember(final MemberBackup memberBackup){
            Member member = new Member();

            member.setKey(memberBackup.getBackupKey());
            member.setVersion(memberBackup.getBackupVersion());
            member.setGuild(memberBackup.getGuild());
            member.setRealm(memberBackup.getRealm());
            member.setMemberName(memberBackup.getMemberName());
            member.setMembertype(memberBackup.getMembertype());
            member.setMemberAccount(memberBackup.getMemberAccount());
            member.setOrder(memberBackup.getOrder());
            member.setWishlist(memberBackup.getWishlist());

            memberService.setMember(member, new AsyncCallback<Void>(){

                public void onSuccess(Void result){
                    setInfoMessage("Member:" + memberBackup.getMemberName() + "の復元に成功しました。");
                    clearErrorMessage();
                }

                public void onFailure(Throwable caught){
                    clearInfoMessage();
                    setErrorMessage("Member:" + memberBackup.getMemberName() + "の復元に失敗しました。");
                }
            });
        }
    }
}
